package com.lhgray.sglhome.data.repository

import android.content.Context
import android.net.Uri
import com.freightoa.foundation.net.ApiResult
import com.freightoa.foundation.net.bean.SGLResponse
import com.freightoa.foundation.presentation.repository.BaseRepository
import com.lhgray.sglhome.data.network.api.HomeServer
import com.lhgray.sglhome.common.utlis.FileUtils.compressImageToRequestBody
import com.lhgray.sglhome.common.utlis.FileUtils.getFileNameFromUri
import dagger.hilt.android.qualifiers.ApplicationContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import javax.inject.Inject

/**
 * 作者：lhgray on 2025/4/1.
 * 邮箱：lhgray@163.com
 * 文件：com.lhgray.sglhome.repository
 */
class UploadImageRepository @Inject constructor(
    val homeServer: HomeServer,
    @ApplicationContext private val context: Context
) : BaseRepository {


    suspend fun uploadPhoto(
        uris: List<Uri?>?,
        sourceTable: String,
        sourceId: String,
        editSubject: String,
        editDetail: String
    ): ApiResult<SGLResponse<String>> {
        val map: MutableMap<String, RequestBody> = HashMap()
        map["source_id"] = toRequestBody(sourceId)
        map["source_table"] = toRequestBody(sourceTable)
        map["subject"] = toRequestBody(editSubject)
        map["content"] = toRequestBody(editDetail)
        val createPartFromUri = createPartFromUri(context, uris)
        return homeServer.postMemo("1", map, createPartFromUri)
    }

    private fun createPartFromUri(context: Context, uris: List<Uri?>?): List<MultipartBody.Part> {
        val mutableListOf = mutableListOf<MultipartBody.Part>()
        uris?.forEach {
            it?.let {
                val fileNameFromUri = getFileNameFromUri(context, it)
                compressImageToRequestBody(context, it)?.let { body ->
                    mutableListOf.add(
                        MultipartBody.Part.createFormData(
                            "file",
                            fileNameFromUri,
                            body
                        )
                    )
                }
            }
        }
        return mutableListOf
    }




    private fun toRequestBody(value: String?): RequestBody {
        val s = value ?: ""
        return s.toRequestBody("text/plain".toMediaType())
    }
}